package studyguide.ch06;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class DisplayableSampleMidlet extends MIDlet {

	private final TextBox textBoxA;
	private final TextBox textBoxB;
	
	private final Command exitCommand;
	private final Command goToBCommand;
	private final Command backToACommand;
	private final Command okOneCommand;
	private final Command okTwoCommand;
	
	private final Display display;
	
	private class SampleCommandListener implements CommandListener {

		public void commandAction(Command c, Displayable d) {
			if (c == exitCommand) {
				destroyApp(true);
				notifyDestroyed();
			} else if (c == goToBCommand) {
				display.setCurrent(textBoxB);
			} else if (c == backToACommand) {
				display.setCurrent(textBoxA);
			} else if (c == okOneCommand) {
				System.out.println("Ok One");
			} else if (c == okTwoCommand) {
				System.out.println("Ok Two");
			} else {
				throw new RuntimeException("UNKNOWN COMMAND" + c);
			}
		}
		
	}
	
	public DisplayableSampleMidlet() {
		System.out.println("Running constructor");
		textBoxA = new TextBox(
				"First Screen",
				"First displayable",
				50,
				TextField.UNEDITABLE);
		textBoxB = new TextBox(
				"Second Screen",
				"Second Displayable",
				50,
				TextField.UNEDITABLE);
		
		exitCommand = new Command("Exit", Command.EXIT, 1);
		goToBCommand = new Command("Go to next screen", Command.OK, 1);
		backToACommand = new Command("Back to previous", Command.BACK, 1);
		
		okOneCommand = new Command("Ok One", Command.OK, 1);
		okTwoCommand = new Command("Ok Two", Command.OK, 2);
		
		textBoxA.addCommand(exitCommand);
		textBoxA.addCommand(goToBCommand);
		
		textBoxB.addCommand(backToACommand);
		textBoxB.addCommand(okOneCommand);
		textBoxB.addCommand(okTwoCommand);
		
		SampleCommandListener listener = new SampleCommandListener();
		textBoxA.setCommandListener(listener);
		textBoxB.setCommandListener(listener);
		
		display = Display.getDisplay(this);
	}
	
	protected void destroyApp(boolean unconditional) {
		System.out.println("Exiting application");
	}

	protected void pauseApp() {
		System.out.println("Pausing application");
	}

	protected void startApp() throws MIDletStateChangeException {
		System.out.println("Starting (or restarting) application");
		// Always starts on first screen
		display.setCurrent(textBoxA);
	}

}
